import React, { Fragment } from 'react';
import { Button, Select, Form, Input, Modal, Radio } from "antd";
import { Map } from 'react-amap';
import { Row, Col } from "antd";
import styles from './point.picker.css';
import { getCoordinateList } from '../../api/ComponentApi'
const { Option } = Select

class FormPointPicker extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                modalVisible: false,
                value: "",
                type: "WGS84",
                lng: "",
                lat: "",
                marker: {},
                riverName: '',
                options: []
            }
        }

        handleOnOk = () => {
            let obj = {};
            obj[this.props.field] = this.state.value;
            this.props.form.setFieldsValue(obj);
            this.setState({
                modalVisible: false
            });
        };

        handleOnCancel = () => {
            this.setState({
                modalVisible: false
            })
        };

        //显示弹框
        showModal = () => {
            this.setState({
                modalVisible: true
            })
        };

        //地图事件
        events = {
            click: (e) => {
                this.setState({
                    lng: e.lnglat.lng,
                    lat: e.lnglat.lat
                });
                this.transform();
                console.log(e);
                let marker = new window.AMap.Marker({
                    icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
                    position: [e.lnglat.lng, e.lnglat.lat],
                    offset: new window.AMap.Pixel(-13, -30)
                })
                this.setState({
                    marker: marker
                })
                this.state.marker.setMap(window.ins);
            },
            created: (ins) => {
                window.ins = ins
                    // window.AMap.plugin(['AMap.Autocomplete','AMap.PlaceSearch'],function(){
                    //     var autoOptions = {
                    //         //输入框id
                    //         input: "keyword"
                    //     };
                    //     console.log(ins)
                    //     console.log(window.AMap)
                    //     let autocomplete= new  window.AMap.Autocomplete(autoOptions);
                    //     var placeSearch = new  window.AMap.PlaceSearch({
                    //         map:ins
                    //     });
                    //     window.AMap.event.addListener(autocomplete, "select", function(e){
                    //         console.log(e)
                    //         placeSearch.setCity(e.poi.adcode);
                    //         placeSearch.search(e.poi.name)
                    //         getCoordinateList({
                    //             // topNum:3,
                    //             river_name:e.poi.name
                    //         }).then(data=>{
                    //             console.log(data)
                    //             if(data.data.data.length){
                    //                 let path = data.data.data[0].points;
                    //                 var polygon = new window.AMap.Polygon({
                    //                     path: path,
                    //                     strokeColor: "#FF33FF", 
                    //                     strokeWeight: 6,
                    //                     strokeOpacity: 0.2,
                    //                     fillOpacity: 0.4,
                    //                     fillColor: '#1791fc',
                    //                     zIndex: 50,
                    //                 })
                    //                 console.log(polygon)
                    //                 console.log(window.AMap.Map)
                    //                 ins.add(polygon)
                    //             }
                    //         })
                    //     });
                    // });
            }
        };


        fetch = (value) => {
            let timeout;
            if (timeout) {
                clearTimeout(timeout);
                timeout = null;
            }
            this.fake(value)
            timeout = setTimeout(this.fake, 300);
        }
        fake = (value) => {
            getCoordinateList({
                // topNum:3,
                river_name: value
            }).then(data => {
                if (data.data.data.length) {
                    // 处理下拉选项得值
                    let options = []
                    for (let i in data.data.data) {
                        let obj = {
                            value: data.data.data[i].name,
                            text: data.data.data[i].name
                        }
                        options.push(obj)
                    }
                    this.setState({
                        options: options
                    })
                    console.log(this.state.options)
                }
            })
        }
        onChangeKey = (value) => {
            console.log(value)
            let ins = window.ins;
            getCoordinateList({
                river_name: value
            }).then(data => {
                if (data.data.data.length) {
                    ins.setZoomAndCenter(18, data.data.data[0].centre)
                    this.setState({
                        riverName: data.data.data[0].name
                    })
                    let path = data.data.data[0].points;
                    let polygon = new window.AMap.Polygon({
                        path: path,
                        strokeColor: "#FF0000",
                        strokeWeight: 6,
                        strokeOpacity: 0.2,
                        fillOpacity: 0.9,
                        fillColor: '#1791fc',
                        zIndex: 50,
                    })
                    ins.add(polygon)
                }
            })
        }
        onSearch = (e) => {
            this.fetch(e);
        }
        cancelMarker = () => {
                if (this.state.marker) {
                    console.log(this.state.marker)
                    this.state.marker.setMap(null);
                    this.state.marker = null;
                }
            }
            // 处理坐标系类型改变
        handleOnchange = (e) => {
            let that = this;
            this.setState({
                type: e.target.value
            }, function() {
                that.transform();
            });
        };

        //坐标转换
        transform = () => {
            console.log("当前坐标系类型:", this.state.type);
            console.log("转换前经纬度:", this.state.value);
            let value;
            if (this.state.type === "WGS84") {
                value = this.gcj02towgs84(this.state.lng, this.state.lat)
            } else if (this.state.type === "BD09") {
                value = this.gcj02tobd09(this.state.lng, this.state.lat)
            } else {
                value = [this.state.lng, this.state.lat]
            }
            this.setState({
                value: value[0] + "," + value[1]
            });
        };

        //坐标转换方法
        x_PI = 3.14159265358979324 * 3000.0 / 180.0;
        PI = 3.1415926535897932384626;
        a = 6378245.0;
        ee = 0.00669342162296594323;

        //火星坐标系 (GCJ-02) 与百度坐标系 (BD-09) 的转换
        gcj02tobd09 = (lng, lat) => {
            let z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * this.x_PI);
            let theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * this.x_PI);
            let bd_lng = z * Math.cos(theta) + 0.0065;
            let bd_lat = z * Math.sin(theta) + 0.006;
            return [bd_lng, bd_lat]
        };

        //GCJ02 转换为 WGS84
        gcj02towgs84 = (lng, lat) => {
            if (this.out_of_china(lng, lat)) {
                return [lng, lat]
            } else {
                let dlat = this.transformlat(lng - 105.0, lat - 35.0);
                let dlng = this.transformlng(lng - 105.0, lat - 35.0);
                let radlat = lat / 180.0 * this.PI;
                let magic = Math.sin(radlat);
                magic = 1 - this.ee * magic * magic;
                let sqrtmagic = Math.sqrt(magic);
                dlat = (dlat * 180.0) / ((this.a * (1 - this.ee)) / (magic * sqrtmagic) * this.PI);
                dlng = (dlng * 180.0) / (this.a / sqrtmagic * Math.cos(radlat) * this.PI);
                let mglat = lat + dlat;
                let mglng = lng + dlng;
                return [lng * 2 - mglng, lat * 2 - mglat]
            }
        };

        transformlat = (lng, lat) => {
            let ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng));
            ret += (20.0 * Math.sin(6.0 * lng * this.PI) + 20.0 * Math.sin(2.0 * lng * this.PI)) * 2.0 / 3.0;
            ret += (20.0 * Math.sin(lat * this.PI) + 40.0 * Math.sin(lat / 3.0 * this.PI)) * 2.0 / 3.0;
            ret += (160.0 * Math.sin(lat / 12.0 * this.PI) + 320 * Math.sin(lat * this.PI / 30.0)) * 2.0 / 3.0;
            return ret
        };

        transformlng = (lng, lat) => {
            var ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng));
            ret += (20.0 * Math.sin(6.0 * lng * this.PI) + 20.0 * Math.sin(2.0 * lng * this.PI)) * 2.0 / 3.0;
            ret += (20.0 * Math.sin(lng * this.PI) + 40.0 * Math.sin(lng / 3.0 * this.PI)) * 2.0 / 3.0;
            ret += (150.0 * Math.sin(lng / 12.0 * this.PI) + 300.0 * Math.sin(lng / 30.0 * this.PI)) * 2.0 / 3.0;
            return ret
        };

        //判断是否在国内，不在国内则不做偏移
        out_of_china = (lng, lat) => {
            return (lng < 72.004 || lng > 137.8347) || ((lat < 0.8293 || lat > 55.8271) || false);
        };

        render() {
                const plugins = ['Scale', 'ToolBar', 'MapType', 'OverView'];
                const { getFieldDecorator } = this.props.form;
                const options = this.state.options.map(d => < Option key = { d.value } > { d.text } < /Option>)
                    return ( <
                        Fragment >
                        <
                        Modal visible = { this.state.modalVisible }
                        width = { 1200 }
                        maskClosable = { false }
                        title = { "地图坐标选择" }
                        okText = "确认选择"
                        onCancel = { this.handleOnCancel }
                        onOk = { this.handleOnOk }
                        zIndex = { 10000000 }
                        bodyStyle = {
                            { padding: 0 } } >
                        <
                        div style = {
                            { width: '100%', height: '650px' } } >
                        <
                        div style = {
                            { width: '100%', height: '50px', position: 'absolute', zIndex: 100000000, left: "20px" } } >
                        <
                        Row gutter = { 10 } >
                        <
                        Col span = { 6 } >
                        <
                        Select value = { this.state.riverName }
                        showSearch style = {
                            { color: 'black' } }
                        onChange = { this.onChangeKey }
                        onSearch = { this.onSearch }
                        placeholder = { "输入地址搜索" }
                        showArrow = { false }
                        allowClear > { options } <
                        /Select> <
                        /Col> <
                        Col span = { 6 } >
                        <
                        Input style = {
                            { color: 'black' } }
                        placeholder = { "坐标选取结果" }
                        value = { this.state.value }
                        disabled >
                        <
                        /Input> <
                        /Col> <
                        Col span = { 6 } >
                        <
                        Radio.Group onChange = { this.handleOnchange }
                        defaultValue = { "WGS84" } >
                        <
                        Radio.Button value = "WGS84" > 国际通用 < /Radio.Button> <
                        Radio.Button value = "GCJ02" > 高德坐标 < /Radio.Button> <
                        Radio.Button value = "BD09" > 百度坐标 < /Radio.Button> <
                        /Radio.Group> <
                        /Col> <
                        Col span = { 6 } >
                        <
                        Button type = "primary"
                        onClick = { this.cancelMarker } > 取消扎点标记 < /Button> <
                        /Col> <
                        /Row> <
                        /div> <
                        Map amapkey = { '9df1dcb5acc420aed8fc034c4a46a75e' }
                        plugins = { plugins }
                        events = { this.events }
                        /> <
                        /div> <
                        /Modal> <
                        Form.Item label = "经纬度选择" > {
                            getFieldDecorator(this.props.field ? this.props.field : "default_lng_lat", { initialValue: this.props.initialValue ? this.props.initialValue : "" })( <
                                Input addonAfter = { < span onClick = { this.showModal } > 选择经纬度 < /span>} placeholder={this.props.placeholder ? this.props.placeholder : "输入或选择经纬度坐标"}/ > )
                            } <
                            /Form.Item> <
                            /Fragment>

                        );
                    }
                }

                export default FormPointPicker;